package com.gonsin.gmessage.logic.websocket;//package com.gonsin.venus.websocket.entity;

import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;

@Slf4j
@Component
@ServerEndpoint(value = "/websocket")
public class ClientHandler {

    /**
     *
     * 用户连接时触发，我们将其添加到
     * 保存客户端连接信息的socketServers中
     */
    @OnOpen
    public void onOpen(Session session){
        WebSocketSessionContainer webSocketSessionContainer = WebSocketSessionContainer.getInstance();
        webSocketSessionContainer.addSession(session.getId(), new WebSocketSession(session, webSocketSessionContainer));
    }

    /**
     * 收到客户端发送信息时触发
     * 我们将其推送给客户端(niezhiliang9595)
     * 其实也就是服务端本身，为了达到前端聊天效果才这么做的
     */
    @OnMessage
    public void onMessage(Session session, String text) throws Exception {
        MessageBo message = new Gson().fromJson(text, MessageBo.class);
        WebSocketSessionContainer webSocketSessionContainer = WebSocketSessionContainer.getInstance();
        WebSocketSession socketSession = webSocketSessionContainer.getSession(session.getId());
        socketSession.channelRead(message);
    }

    /**
     *
     * 连接关闭触发，通过sessionId来移除
     * socketServers中客户端连接信息
     */
    @OnClose
    public void onClose(Session session){
        WebSocketSessionContainer webSocketSessionContainer = WebSocketSessionContainer.getInstance();
        WebSocketSession socketSession = webSocketSessionContainer.getSession(session.getId());
        socketSession.channelInactive();
    }

    /**
     *
     * 发生错误时触发
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        WebSocketSessionContainer webSocketSessionContainer = WebSocketSessionContainer.getInstance();
        WebSocketSession socketSession = webSocketSessionContainer.getSession(session.getId());
        socketSession.exceptionCaught(error);
    }

}
